package dongze.com.ckdj.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.databinding.Observable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.BR;
import dongze.com.ckdj.R;
import dongze.com.ckdj.dagger.component.UserComponent;
import dongze.com.ckdj.data.entity.request.AddVinMapRequestBody;
import dongze.com.ckdj.data.entity.response.BrandResponse;
import dongze.com.ckdj.data.entity.response.GetLaneResponse;
import dongze.com.ckdj.data.entity.response.GetParkingAreaResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.databinding.InformationItemEditTextNumBinding;
import dongze.com.ckdj.databinding.InformationItemRadioBinding;
import dongze.com.ckdj.databinding.InformationItemSpinnerBinding;
import dongze.com.ckdj.databinding.InformationItemTextBinding;
import dongze.com.ckdj.databinding.ParkinglotListItemBinding;
import dongze.com.ckdj.databinding.VehicleNumberItemBinding;
import dongze.com.ckdj.databinding.model.InformationItemRadioModel;
import dongze.com.ckdj.databinding.model.InformationItemSpinnerModel;
import dongze.com.ckdj.databinding.model.InformationItemTextModel;
import dongze.com.ckdj.databinding.model.ParkingLotListItemModel;
import dongze.com.ckdj.databinding.model.VehicleNumberModel;
import dongze.com.ckdj.map.MapUtil;
import dongze.com.ckdj.persistence.dao.DaoSession;
import dongze.com.ckdj.util.MyLog;
import dongze.com.ckdj.util.Util;
import io.reactivex.observers.DisposableObserver;


/**
 * Created by fanqwz on 2017/9/14.
 */

public class ParkingLotActivity extends ProgressableActivity {
    private static final String TAG = ParkingLotActivity.class.getSimpleName();
    private static final int BACK_PRESSED_MSG = 1027;
    private static final String ORDER_DEC = "递减";
    private static final String ORDER_INC = "递增";

    @BindView(R.id.basic_info_container)
    GridLayout mBasicInfoLayout;
    @BindView(R.id.vehicle_number_container)
    ViewGroup mVehicleNumberContainer;
    @BindView(R.id.content)
    GridLayout mContent;
    @BindView(R.id.list)
    ListView listView;

    MapUtil mapUtil;
    @Inject
    User mUser;
    @Inject
    DaoSession daoSession;

    InformationItemTextModel mTimeModel = new InformationItemTextModel();
    InformationItemTextModel mUserModel = new InformationItemTextModel();
    VehicleNumberModel mVehicleNumberModel = new VehicleNumberModel();
    InformationItemSpinnerModel mBrandModel = new InformationItemSpinnerModel();
    InformationItemSpinnerModel mParkLotModel = new InformationItemSpinnerModel();
    InformationItemSpinnerModel mLaneModel = new InformationItemSpinnerModel();
    InformationItemRadioModel mOrderModel = new InformationItemRadioModel();
    InformationItemTextModel mPositionModel = new InformationItemTextModel();
    private DisposableObserver mPendingDisposable;

    android.os.Handler mHandler;
    String mCurrentVehicleNumber;
    List<BrandResponse> brands;
    List<GetParkingAreaResponse> parkLots;
    List<GetLaneResponse> lanes;
    ArrayList<Data> listItems = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_lot);
        ButterKnife.bind(this);
        mHandler = new Handler(getMainLooper());
        mapUtil = new MapUtil(getAppCompenent());

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(mTimeReceiver, intentFilter);

        if (getComponent(UserComponent.class) != null) {
            getComponent(UserComponent.class).inject(this);
        } else {
            finish();
            return;
        }

        mTimeModel.setKey("当前时间");
        mTimeModel.setValue(Util.getCurrentTime(this));
        addBasicInfoItem(mTimeModel);

        mUserModel.setKey("登陆人员");
        mUserModel.setValue(mUser.getRemark() + "-" + mUser.getUser_name());
        addBasicInfoItem(mUserModel);

        mBrandModel.setKey("品牌");
        addBrandName(mBrandModel);

        mParkLotModel.setKey("区域");
        mParkLotModel.addOnPropertyChangedCallback(mOnParkLotChanged);
        addDropDownInfoItem(mParkLotModel);

        mLaneModel.setKey("车道");
        addDropDownInfoItem(mLaneModel);

        mOrderModel.setKey("顺序");
        mOrderModel.setValues(new String[]{ORDER_INC, ORDER_DEC});
        mOrderModel.setPosition(ORDER_INC);
        addOrderModel(mOrderModel);

        mPositionModel.setKey("位置");
        mPositionModel.setValue("1");
        addPositionModel(mPositionModel);

        addVehicleNumber(mVehicleNumberModel);

        ParkinglotListItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.parkinglot_list_item, null, false);
        binding.setParkingLotListItem(new ParkingLotListItemModel());
        binding.getParkingLotListItem().idx.set(" ");
        binding.getParkingLotListItem().vin.set("车架号");
        binding.getParkingLotListItem().pos.set("位置");
        listView.addHeaderView(binding.getRoot() , null, false);
        listView.setAdapter(listAdapter);

        loadBrands();
        loadParklot();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.parking_lot, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.query) {
            query();
            return true;
        } else if (item.getItemId() == R.id.save) {
            save();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mTimeReceiver);
        mapUtil.dispose();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (mHandler.hasMessages(BACK_PRESSED_MSG)) {
            super.onBackPressed();
        } else {
            Toast.makeText(this, "再次按下返回键退出当前页面", Toast.LENGTH_SHORT).show();
            mHandler.sendMessageDelayed(mHandler.obtainMessage(BACK_PRESSED_MSG), 1500);
        }
    }

    private void addBasicInfoItem(InformationItemTextModel model) {
        InformationItemTextBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_text, mBasicInfoLayout, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemText(model);
        int count = mBasicInfoLayout.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1, 0.5f), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mBasicInfoLayout.addView(binding.getRoot(), params);
    }

    private void addDropDownInfoItem(InformationItemSpinnerModel model) {
        InformationItemSpinnerBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_spinner, mContent, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemSpinner(model);
        int count = mContent.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mContent.getChildCount() / count, 1), GridLayout.spec(mContent.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mContent.getChildCount() / count, 1, 0.5f), GridLayout.spec(mContent.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mContent.addView(binding.getRoot(), params);
    }

    private void addBrandName(InformationItemSpinnerModel model) {
        InformationItemSpinnerBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_spinner, mBasicInfoLayout, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemSpinner(model);
//        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.name_plate_brand_width), ViewGroup.LayoutParams.WRAP_CONTENT);
//        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
//        params.setMargins(margin, margin, margin, margin);
//        params.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
        int count = mBasicInfoLayout.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mBasicInfoLayout.getChildCount() / count, 1, 0.5f), GridLayout.spec(mBasicInfoLayout.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mBasicInfoLayout.addView(binding.getRoot(), params);
    }

    private void addOrderModel(InformationItemRadioModel model) {
        InformationItemRadioBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_radio, mContent, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemRadio(model);
        int count = mContent.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mContent.getChildCount() / count, 1), GridLayout.spec(mContent.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mContent.getChildCount() / count, 1, 0.5f), GridLayout.spec(mContent.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mContent.addView(binding.getRoot(), params);
    }

    private void addPositionModel(InformationItemTextModel model) {
        InformationItemEditTextNumBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.information_item_edit_text_num, mContent, false);
        binding.getRoot().setTag(binding);
        binding.setVehicleInformationItemText(model);
        int count = mContent.getColumnCount();
        GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(mContent.getChildCount() / count, 1), GridLayout.spec(mContent.getChildCount() % count, 1));
        params.width = (getResources().getDisplayMetrics().widthPixels) / count;

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            params = new GridLayout.LayoutParams(GridLayout.spec(mContent.getChildCount() / count, 1, 0.5f), GridLayout.spec(mContent.getChildCount() % count, 1, 0.5f));
//        }

        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        mContent.addView(binding.getRoot(), params);
    }

    private void addVehicleNumber(VehicleNumberModel model) {
        final VehicleNumberItemBinding vehicleNumberItemBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.vehicle_number_item, mVehicleNumberContainer, false);
        model.setKey("车架号");
        model.setOnItemClickListener(mOnVehicleNumberClick);
        vehicleNumberItemBinding.setInformationItemAutoCompleteTextModel(model);
        model.addOnPropertyChangedCallback(mOnVehicleNumberChangedListener);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = getResources().getDimensionPixelSize(R.dimen.basic_info_item_margin);
        params.setMargins(margin, margin, margin, margin);
        params.gravity = Gravity.CENTER;
        mVehicleNumberContainer.addView(vehicleNumberItemBinding.getRoot(), params);
        setVinFocus();
    }

    private void setVinFocus() {
        mVehicleNumberContainer.post(new Runnable() {
            @Override
            public void run() {
                ViewGroup viewGroup = (ViewGroup) mVehicleNumberContainer.getChildAt(0);
                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    if (viewGroup.getChildAt(i) instanceof EditText) {
                        viewGroup.getChildAt(i).requestFocus();
                        break;
                    }
                }
            }
        });

    }

    private void loadBrands() {
        mapUtil.getBrands("1",
                new DisposableObserver<List<BrandResponse>>() {
                    @Override
                    protected void onStart() {
                        super.onStart();
                        doProcessing();
                    }

                    @Override
                    public void onNext(List<BrandResponse> value) {
                        String pref = Util.getPreference(ParkingLotActivity.this, Util.PREF_SELECTED_BRAND, null);
                        String[] entries = new String[value.size()];

                        for (int i = 0; i < value.size(); i++) {
                            entries[i] = value.get(i).getBrand_name();
                        }

                        mBrandModel.setValues(entries);
                        mBrandModel.setPosition(0);
                        brands = value;

                        for (int i = 0; i < value.size(); i++) {
                            if (TextUtils.equals(value.get(i).getBrand_code(), pref))
                                mBrandModel.setPosition(i);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        MyLog.e(TAG, "onError: ", e);
                        new AlertDialog.Builder(ParkingLotActivity.this)
                                .setMessage(e.getMessage())
                                .create()
                                .show();
                        finishProcessing();
                    }

                    @Override
                    public void onComplete() {
                        finishProcessing();
                        setVinFocus();
                    }
                });
    }

    private void loadParklot() {
        mapUtil.getParkingArea(new DisposableObserver<List<GetParkingAreaResponse>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(List<GetParkingAreaResponse> value) {
                String[] entries = new String[value.size()];

                for (int i = 0; i < value.size(); i++) {
                    entries[i] = value.get(i).getQyName();
                }

                mParkLotModel.setValues(entries);
                mParkLotModel.setPosition(0);
                parkLots = value;
            }

            @Override
            public void onError(Throwable e) {
                new AlertDialog.Builder(ParkingLotActivity.this)
                        .setMessage(e.getMessage())
                        .create()
                        .show();
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
                loadLane();
                setVinFocus();
            }
        });
    }

    private void loadLane() {
        if (parkLots == null || mParkLotModel.getPosition() >= parkLots.size()
                || mParkLotModel.getPosition() < 0)
            return;

        String areaID = parkLots.get(mParkLotModel.getPosition()).getQyID();
        mapUtil.getLane(areaID, new DisposableObserver<List<GetLaneResponse>>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(List<GetLaneResponse> value) {
                String[] entries = new String[value.size()];

                for (int i = 0; i < value.size(); i++) {
                    entries[i] = value.get(i).getLaneName();
                }

                mLaneModel.setValues(entries);
                mLaneModel.setPosition(0);
                lanes = value;
            }

            @Override
            public void onError(Throwable e) {
                new AlertDialog.Builder(ParkingLotActivity.this)
                        .setMessage(e.getMessage())
                        .create()
                        .show();
                finishProcessing();
            }

            @Override
            public void onComplete() {
                finishProcessing();
                setVinFocus();
            }
        });
    }

    private void onVinAdd(String vin) {
        mVehicleNumberModel.setEntries(null);
        mVehicleNumberModel.setValue(null);

        for (int i = 0; i < listItems.size(); i++) {
            Data d = listItems.get(i);
            if (TextUtils.equals(d.vin, vin)) {
                new AlertDialog.Builder(this)
                        .setMessage("车架号" + vin + "与第条" + (listItems.size() - i) + "记录车架号重复")
                        .create()
                        .show();
                return;
            }

            try {
                if (TextUtils.equals(d.areaID, parkLots.get(mParkLotModel.getPosition()).getQyID())
                        && TextUtils.equals(d.areaName, parkLots.get(mParkLotModel.getPosition()).getQyName())
                        && TextUtils.equals(d.laneID, lanes.get(mLaneModel.getPosition()).getLaneID())
                        && TextUtils.equals(d.laneName, lanes.get(mLaneModel.getPosition()).getLaneName())
                        && d.pos == Integer.parseInt(mPositionModel.getValue())) {
                    new AlertDialog.Builder(this)
                            .setMessage("当前位置与第条" + (listItems.size() - i) + "记录位置重复")
                            .create()
                            .show();
                    return;
                }
            } catch (Exception e) {
                new AlertDialog.Builder(this)
                        .setMessage("添加失败")
                        .create()
                        .show();
                return;
            }
        }

        mCurrentVehicleNumber = vin;
        mVehicleNumberModel.setHint(mCurrentVehicleNumber);

        try {
            if (Integer.parseInt(mPositionModel.getValue()) <= 0) {
                new AlertDialog.Builder(this)
                        .setMessage("位置不能小于1")
                        .create()
                        .show();

            }

            Data data = new Data();
            data.vin = vin;
            data.areaID = parkLots.get(mParkLotModel.getPosition()).getQyID();
            data.areaName = parkLots.get(mParkLotModel.getPosition()).getQyName();
            data.laneID = lanes.get(mLaneModel.getPosition()).getLaneID();
            data.laneName = lanes.get(mLaneModel.getPosition()).getLaneName();
            data.pos = Integer.parseInt(mPositionModel.getValue());
            listItems.add(0, data);
            listAdapter.notifyDataSetChanged();

            mPositionModel.setValue(String.valueOf(
                    TextUtils.isEmpty(mPositionModel.getValue()) ? "0" : Integer.parseInt(mPositionModel.getValue())
                            + (ORDER_INC.equals(mOrderModel.getPosition()) ? 1 : -1)).trim());
        } catch (Exception e) {
            e.printStackTrace();
            new AlertDialog.Builder(this)
                    .setMessage(e.getMessage())
                    .create()
                    .show();
        }
    }

    private void query() {
        startActivity(new Intent(getApplicationContext(), ParkLotQueryActivity.class));
    }

    private void save() {
        if (listItems.size() == 0) {
            new AlertDialog.Builder(this)
                    .setMessage("没有内容")
                    .create()
                    .show();
            return;
        }

        List<AddVinMapRequestBody> arr = new ArrayList<>(listItems.size());

        for (int i = 0; i < listItems.size(); i++) {
            Data data = listItems.get(i);
            AddVinMapRequestBody addVinMapRequestBody = new AddVinMapRequestBody();
            addVinMapRequestBody.setVin(data.vin);
            addVinMapRequestBody.setSort(data.pos);
            addVinMapRequestBody.setQyID(data.areaID);
            addVinMapRequestBody.setQyName(data.areaName);
            addVinMapRequestBody.setLaneID(data.laneID);
            addVinMapRequestBody.setLaneName(data.laneName);
            addVinMapRequestBody.setUserNo(mUser.getUser_no());
            addVinMapRequestBody.setUserName(mUser.getUser_name());
            arr.add(addVinMapRequestBody);
        }

        mapUtil.addVinMap(arr, new DisposableObserver<String>() {
            @Override
            protected void onStart() {
                super.onStart();
                doProcessing();
            }

            @Override
            public void onNext(String value) {
                Toast.makeText(ParkingLotActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                finishProcessing();
                new AlertDialog.Builder(ParkingLotActivity.this)
                        .setMessage(e.getMessage())
                        .create()
                        .show();
            }

            @Override
            public void onComplete() {
                finishProcessing();
                mCurrentVehicleNumber = null;
                mVehicleNumberModel.setEntries(null);
                mVehicleNumberModel.setValue(null);
                mVehicleNumberModel.setHint(null);
                listItems.clear();
                listAdapter.notifyDataSetChanged();

                try {
                    if (lanes.size() != 0 && lanes.size() >= mLaneModel.getPosition()) {
                        lanes.remove(mLaneModel.getPosition());
                        String[] entries = new String[lanes.size()];
                        for (int i = 0; i < lanes.size(); i++) {
                            entries[i] = lanes.get(i).getLaneName();
                        }
                        mLaneModel.setValues(entries);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private class Data {
        String areaID;
        String areaName;
        String laneID;
        String laneName;
        int pos;
        String vin;
    }

    BaseAdapter listAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return listItems.size();
        }

        @Override
        public Object getItem(int position) {
            return listItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                ParkinglotListItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.parkinglot_list_item, parent, false);
                binding.setParkingLotListItem(new ParkingLotListItemModel());
                convertView = binding.getRoot();
                convertView.setTag(binding.getParkingLotListItem());
            }

            ParkingLotListItemModel model = (ParkingLotListItemModel) convertView.getTag();
            final Data data = listItems.get(position);
            model.idx.set(String.valueOf(listItems.size() - position));
            model.vin.set(data.vin);
            model.pos.set(data.areaName + "-" + data.laneName + "-" + data.pos);
            model.onClick.set(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listItems.remove(data);
                    listAdapter.notifyDataSetChanged();
                }
            });
            return convertView;
        }
    };

    private Observable.OnPropertyChangedCallback mOnParkLotChanged = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            if (propertyId == BR.position) {
                loadLane();
            }
        }
    };

    private Observable.OnPropertyChangedCallback mOnVehicleNumberChangedListener = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            if (propertyId == BR.value) {
                mHandler.removeCallbacks(mGetAutoCompleteDateRunnable);
                mHandler.postDelayed(mGetAutoCompleteDateRunnable, 300);
            }
        }
    };

    private Runnable mGetAutoCompleteDateRunnable = new Runnable() {
        @Override
        public void run() {
            MyLog.d(TAG, "run:mGetAutoCompleteDateRunnable");

            if (mVehicleNumberModel.getValue() == null
                    || mVehicleNumberModel.getValue().length() <= 3
                    || mVehicleNumberModel.getValue().equals(mCurrentVehicleNumber)
                    || mBrandModel.getValues() == null
                    || brands == null)
                return;

            if (mPendingDisposable != null && !mPendingDisposable.isDisposed()) {
                mPendingDisposable.dispose();
            }

            mPendingDisposable = new DisposableObserver<List<Pair<String, String>>>() {
                @Override
                protected void onStart() {
                    super.onStart();
//                    showProgressBar();
                    mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<查询中......>", null)));
                }

                @Override
                public void onNext(List<Pair<String, String>> value) {
                    MyLog.d(TAG, "onNext: mGetAutoCompleteDateRunnable");
                    mVehicleNumberModel.setEntries(value);
                    if (value.size() == 1) {
                        // 只有一个结果自动填充并开始做下一步查询
                        onVinAdd(value.get(0).first);
                    } else if (value.size() == 0) {
                        mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<找不到车架号>", null)));
                    }
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    mVehicleNumberModel.setEntries(Arrays.asList(new Pair<String, String>("<查询出错>", null)));
//                    hideProgressBar();
                }

                @Override
                public void onComplete() {
//                    hideProgressBar();
                }
            };

            mapUtil.mapInformationItemAutoCompleteTextModel(
                    mVehicleNumberModel.getValue(),
                    brands.get(mBrandModel.getPosition()).getBrand_code(), ""
                    , mPendingDisposable);
        }
    };


    AdapterView.OnItemClickListener mOnVehicleNumberClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // start get detail info
            MyLog.d(TAG, "onItemClick: ");
            mHandler.removeCallbacks(mGetAutoCompleteDateRunnable);

            //check
            try {
                if (mVehicleNumberModel.getValue() == null
                        || !mVehicleNumberModel.getValue().equals(
                        mVehicleNumberModel.getEntries().get(position).first)
                        || (mVehicleNumberModel.getValue().startsWith("<") && mVehicleNumberModel.getValue().endsWith(">"))) {
                    MyLog.e(TAG, "onItemClick: check data consistency failed");
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }

            onVinAdd(mVehicleNumberModel.getValue());
        }
    };


    BroadcastReceiver mTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                mTimeModel.setValue(Util.getCurrentTime(ParkingLotActivity.this));
            }
        }
    };

}
